<?php

namespace App\Http\Service;

use App\Libs\HttpCurlLibrary;
use Illuminate\Support\Facades\Log;
use App\Services\Ip2RegionService;
use Illuminate\Support\Facades\DB;
use App\Http\Service\UserService;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;

#获取佣金 补贴 
class MoneyService extends BaseService
{
    private $ip2RegionService;
    
    // 静态变量定义 - 使用不同的名称避免冲突
    private static $initialized = false;
    private static $staticUserService;
    private static $staticPlatformRateType1;
    private static $staticPlatformRateType2;
    private static $staticPersonalDetail;
    
    // 实例变量
    private $userService;
    private $platformRateType1;
    private $platformRateType2;
    private $personalDetail;

    public function __construct(UserService $userService)
    {
        parent::__construct();
       
        // 只在第一次初始化时执行
        if (!self::$initialized) {
            self::$staticUserService = $userService;
            self::$staticPlatformRateType1 = $this->getPlatformAllRate(1);
            self::$staticPlatformRateType2 = $this->getPlatformAllRate(2);
            self::$staticPersonalDetail = config('myurl.personal_detail');
            self::$initialized = true;
           // echo "333333;"; // 现在只会输出一次
        }
        
        // 将静态变量赋值给实例变量，方便在非静态方法中使用
        $this->userService = self::$staticUserService;
        $this->platformRateType1 = self::$staticPlatformRateType1;
        $this->platformRateType2 = self::$staticPlatformRateType2;
        $this->personalDetail = self::$staticPersonalDetail;
    }
    
    #获取平台比例 type=1 爆料  type=2 心动日记
    public function getPlatformAllRate($type=1)
    {
        if(empty($type)){
            $type=1;
        }
        if($type==1){
            $data=platform_rate();
        }else if($type==2){
            $data=platform_xdrj_rate();
        }
        
        return $data;
    }
    
    public function getPlatformRate($type=1)
    {
        if(empty($type)){
            $type=1;
        }
        //dd($type);
        if($type==1){
            $data = $this->platformRateType1;
        }else if($type==2){
            $data = $this->platformRateType2;
        }
        return $data;
    }

    #获取用户信息
    public function getUserDate($people_id)
    {
        $data = $this->userService->update_user($people_id);
        return $data;
    }

    #获取用户等级比例
    public function userLevelRate($levelId)
    {
        $data = user_level_rate($levelId);
        return $data;
    }
    
    #获取用户实时总佣金比例
    public function get_total_commission_ing($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true=1,$is_owner=true,$type=1,$update_time="",$product_id="")
    {
        $deal_update_time = date("Y-m-d",strtotime($update_time));
        $now_time = date("Y-m-d");
        
        if($update_time && $product_id){
            #update_time 和 product_id 和 people_id 不为空
            if($deal_update_time == $now_time){
                $result = $this->estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true,$is_owner,$type);
            } else {
                $getinfo_url = $this->personalDetail['url'];
                $user_params = [
                    "product_id" => $product_id,
                    "platform" => $platform_name,
                    "user_id" => $people_id
                ];
                
                $txt_data = [
                    'subsidy_rate' => 0.00,
                    'commission_rate' => 0.00,
                    'product_id' => $product_id,
                    'platform_name' => $platform_name,
                    'time' => date("Y-m-d")
                ];
                
                $pp = $product_id . $txt_data['platform_name'] . $txt_data['time'];
                $cacheKey = 'baoliao:' . md5($pp);
                
                // 尝试从缓存获取
                $cachedResult = cache()->get($cacheKey);
                if ($cachedResult !== null) {
                    $subsidy_rate = $cachedResult['subsidy_rate'];
                    $commission_rate = $cachedResult['commission_rate'];
                    $result = $this->estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true,$is_owner,$type);
                    return $result;
                }
                
                $postdata = json_post($getinfo_url,$user_params);
                $result = [
                    'subsidy_amount' => 0.00,
                    'commission_amount' => 0.00,
                    'total_commission' => 0.00,
                ];

                if(isset($postdata['status']) && $postdata['status'] == '200'){
                    if(isset($postdata['data'])){
                        $userdata = $postdata['data'];
                        #佣金
                        if(isset($userdata['commission'])){
                            $result['commission_amount'] = $userdata['commission'];
                        }
                        #佣金占比
                        if(isset($userdata['commission_rate'])){
                            $txt_data['commission_rate'] = $userdata['commission_rate'];
                        }

                        if(isset($userdata['platform_subsidy'])){
                            $platform_subsidy = $userdata['platform_subsidy'];
                            if(isset($platform_subsidy[0])){
                                $platform_subsidy = $platform_subsidy[0];
                                if(isset($platform_subsidy['subsidy_amount'])){
                                    $result['subsidy_amount'] = $platform_subsidy['subsidy_amount'];
                                }
                                #补贴比例
                                if(isset($platform_subsidy['subsidy_rate'])){
                                    $txt_data['subsidy_rate'] = $platform_subsidy['subsidy_rate'];
                                }
                            }
                        }
                    }
                }
                
                // 写入缓存
                cache()->put($cacheKey, $txt_data, 3600);
                $result['total_commission'] = $result['commission_amount'] + $result['subsidy_amount'];
            }
        } else {
            #为空
            $result = $this->estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true,$is_owner,$type);
        }

        return $result;
    }

    /**
     * 获取补贴金额
     */
    public function subsidyAmount($unit_price,$subsidy_rate,$platform_name,$people_id,$is_rate_true=1,$is_owner=true,$type=1)
    {
        if(empty($type)){
            $type=1;
        }
        
        if($is_rate_true){
            $subsidy_rate = $subsidy_rate/100;
        }

        $platform_rate_arr = $this->getPlatformRate($type);
        $platform_rate = $platform_rate_arr[$platform_name];
        
        if($type==2){
            $levelId = 3;
        }else if($type==1){
            $getUserDate_arr = $this->getUserDate($people_id);
            $levelId = $getUserDate_arr['levelId'];
        }
        
        $user_level_rate = $this->userLevelRate($levelId);
        $subsidy_amount = $unit_price * $subsidy_rate * $platform_rate * $user_level_rate;

        if(!$is_owner && $platform_name == '京东'){
            $subsidy_amount = $subsidy_amount * 0.9;
        }
        
        return $subsidy_amount;
    }

    /**
     * 获取佣金金额
     */
    public function commissionAmount($unit_price,$commission_rate,$platform_name,$people_id,$is_rate_true=1,$is_owner=true,$type=1)
    {
        if(empty($type)){
            $type=1;
        }
        
        if($is_rate_true){
            $commission_rate = $commission_rate/100;
        }

        $platform_rate_arr = $this->getPlatformRate($type);
        $platform_rate = $platform_rate_arr[$platform_name];
        
        if($type==1){
            $getUserDate_arr = $this->getUserDate($people_id);
            $levelId = $getUserDate_arr['levelId'];
        }else if($type==2){
            $levelId = 3;
        }
        
        $user_level_rate = $this->userLevelRate($levelId);
        $commission_amount = $unit_price * $commission_rate * $platform_rate * $user_level_rate;
        
        if(!$is_owner && $platform_name == '京东'){
            $commission_amount = $commission_amount * 0.9;
        }
        
        return $commission_amount;
    }

    /**
     * 获取总佣金金额
     */
    public function estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true=1,$is_owner=true,$type=1)
    {
        if(empty($type)){
            $type=1;
        }
        
        $subsidyAmount = $this->subsidyAmount($unit_price,$subsidy_rate,$platform_name,$people_id,$is_rate_true,$is_owner,$type);
        $commissionAmount = $this->commissionAmount($unit_price,$commission_rate,$platform_name,$people_id,$is_rate_true,$is_owner,$type);
        
        $total_commission = $subsidyAmount + $commissionAmount;
        $result = [
            'subsidy_amount' => $subsidyAmount,
            'commission_amount' => $commissionAmount,
            'total_commission' => $total_commission,
        ];
        
        return $result;
    }

    #获取佣金金额（表数据计算）
    public function commissionAmountTable($unit_price,$commission_rate,$platform_name,$quantity=1,$is_rate_true=1,$is_owner=true)
    {
        if($is_rate_true){
            $commission_rate = $commission_rate/100;
        }

        $commission_amount = $unit_price * $commission_rate;
        
        if(!$is_owner && $platform_name == '京东'){
            $commission_amount = $commission_amount * 0.9;
        }
        
        return $commission_amount;
    }

    #预估佣金
    public function estimated_amount($unit_price,$commission_rate,$platform_name,$people_id,$is_rate_true=1,$is_owner=true)
    {
        if($is_rate_true){
            $commission_rate = $commission_rate/100;
        }

        $platform_rate_arr = $this->getPlatformRate();
        $platform_rate = $platform_rate_arr[$platform_name];
        
        $getUserDate_arr = $this->getUserDate($people_id);
        $levelId = $getUserDate_arr['levelId'];
        $user_level_rate = $this->userLevelRate($levelId);
        
        $estimated_amount = $unit_price * $commission_rate * $platform_rate * $user_level_rate;
        
        if(!$is_owner && $platform_name == '京东'){
            $estimated_amount = $estimated_amount * 0.9;
        }
        
        return $estimated_amount;
    }

    public function purchase_steps($purchase_steps,$quantity,$title,$platform_name,$commission_amount,$unit_price)
    {
        $final_price = $unit_price * $quantity;
        $commission_amount_total = $commission_amount * $quantity;
        
        foreach ($purchase_steps as $key => &$val) {
            #下单
            if($val['type'] == 5){
                if($quantity > 1){
                    $lastunitPrice = ($unit_price - $commission_amount_total) / $quantity;
                    $lastunitPrice = _round($lastunitPrice);
                    $commission_amount_total = _round($commission_amount_total);
                    $val['description'] = "下单{$quantity}件实付{$unit_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元";
                } else {
                    $commission_amount_total = _round($commission_amount_total);
                    $val['description'] = "实付{$final_price}，下单后返利约{$commission_amount_total}元";
                }
            }
        }
        
        return $purchase_steps;
    }
}
